const request = require("https").request;
const { WX_CONFIG } = require("../config/index");
// https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
const getOpenId = (code) => {
  return new Promise((resolve, reject) => {
    const req = request(
      {
        method: "GET",
        hostname: "api.weixin.qq.com",
        path: `/sns/jscode2session?appid=${WX_CONFIG.appId}&secret=${WX_CONFIG.appSecret}&js_code=${code}&grant_type=authorization_code`,
        headers: {
          "Content-Type": "application/json",
        },
      },
      (res) => {
        let data = "";

        // 监听数据流并拼接
        res.on("data", (chunk) => {
          data += chunk;
        });

        // 监听流结束事件
        res.on("end", () => {
          try {
            const parsedData = JSON.parse(data);
            if (res.statusCode !== 200 || parsedData.errcode) {
              return reject(
                new Error(
                  `WeChat API error: ${parsedData.errmsg || "Unknown error"}`
                )
              );
            }
            resolve(parsedData);
          } catch (err) {
            reject(new Error(`Failed to parse response: ${err.message}`));
          }
        });

        // 错误处理
        res.on("error", (err) => {
          reject(new Error(`Response error: ${err.message}`));
        });
      }
    );

    // 请求超时处理
    req.setTimeout(5000, () => {
      req.abort();
      reject(new Error("Request timed out"));
    });

    // 请求错误处理
    req.on("error", (err) => {
      reject(new Error(`Request error: ${err.message}`));
    });

    // 发送请求
    req.end();
  });
};
module.exports = { getOpenId };
